import * as actionType from '../actions/actionType.js';
const initState = {
  cartList: wx.getStorageSync('gy-cart') || []
}
export default (state = initState, action) => {
  switch(action.type) {
    case actionType.ADD_TO_CART: {
      const {
        id,
        count
      } = action.payload.cartItem
      let isExist = state.cartList.some((item) => {
        return item.id === id
      })
      if (isExist) {
        state.cartList = state.cartList.map(item => {
          if (item.id === id) {
            item.count += count
          }
          return item
        })
      } else {
        state.cartList.push(action.payload.cartItem)
      }
      return state;
    }
    case actionType.CART_COUNT_ADD: {
      const {
        id
      } = action.payload
      state.cartList = state.cartList.map(item => {
        if (item.id === id) {
          item.count += 1
        }
        return item
      })
      return state;
    } 
    case actionType.CART_COUNT_REDUCE: {
      const {
        id
      } = action.payload
      state.cartList = state.cartList.map(item => {
        if (item.id === id) {       
            item.count -= 1
        }
        return item
      })
      state.cartList = state.cartList.filter(item => 
        item.count!==0
      )
      return state;
    }
    case actionType.TOGGLE_CHECKED: {
      const {
        id
      } = action.payload
      state.cartList = state.cartList.map(item => {
        if (item.id === id) {
          item.checked = !item.checked
        }
        return item
      })
      return state;
    }
    case actionType.CART_ITEM_DELETE: {
      const {
        id
      } = action.payload
      state.cartList = state.cartList.filter(item => {
        return item.id !== id
      })
      return state;
    }
    case actionType.TOGGLE_ALL_CHECKED: {
      const {
        status
      } = action.payload
      state.cartList = state.cartList.map(item => {
        item.checked = status
        return item
      })
      return state;
    }
    default:
      return state;
  }
}